<?php


namespace app\common\model\mysql;


use app\common\exception\MessageException;

class Category extends BaseModel
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'category';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 模型初始化
    protected static function init()
    {
        // TODO:初始化内容
    }

    // 检查分类名是否存在
    public function checkName($name, $id = null)
    {
        if (!$name) {
            throw new MessageException(['msg' => '分类名不合法']);
        }

        // 设置查询条件
        $condition = ['name' => $name];
        $data = $this->where('name', $name);
        if ($id) {
            $data = $data->where('id', '<>', $id);
        }

        return $data->find();
    }

    public function getList(array $param = [])
    {
        $order = [
            'sort' => 'ASC',
            'update_time'=> 'desc',
            'create_time'=> 'desc',
            'id' => 'desc'
        ];
        $list = $this->where('status', '>','0')->order($order)->select();
        return $list;
    }

    public function getTreeList(array $param = [])
    {
        $list = $this->where('status', '>','0')->select()->toArray();
        return $this->getTreeData($list);
    }

    /**
     * 获取树状列表
     * @param $list
     * @param int $parentId
     * @return array
     */
    private function getTreeData($list, int $parentId = 0)
    {
        $data = [];
        foreach ($list as $key => $item) {
            if ($item['parent_id'] == $parentId) {
                $children = $this->getTreeData($list, $item['id']);
                !empty($children) && $item['children'] = $children;
                $data[] = $item;
                unset($list[$key]);
            }
        }
        return $data;
    }
}